import hashlib
import time
import json, struct
from functools import wraps
from TcpServer import user_data


def get_time():
	now_time = time.strftime('%Y-%m-%d %X')
	return now_time


def send_msg(conn, back_dic):
	data_bytes = json.dumps(back_dic).encode('utf-8')
	header = struct.pack('i', len(data_bytes))
	conn.send(header)
	conn.send(data_bytes)


def get_session(name):
	md5 = hashlib.md5()
	# CPU运行时间...
	md5.update(str(time.clock()).encode('utf-8'))
	md5.update(name.encode('utf-8'))
	return md5.hexdigest()


def login_auth(func):
	@wraps(func)
	def inner(*args, **kwargs):  # args: conn, back_dic
		for value in user_data.alive_user.values():  # [session, user_id]
			if args[1].get('session') == value[0]:
				args[1]['user_id'] = value[1]
				break
		if args[1].get("user_id"):
			func(*args, **kwargs)
		else:
			back_dic = {'flag': False, "msg": '请先去登陆...'}
			send_msg(args[0], back_dic)
	return inner






